package cn.mugutu.webrtc.websocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import cn.mugutu.webrtc.utils.PrintUtil;
import cn.mugutu.webrtc.websocket.util.WebSocketUtil;

//WebSocketHandler 消息处理中心
/**
 * 功能说明：WebSocket处理器 可以继承 {@link TextWebSocketHandler}/
 * {@link BinaryWebSocketHandler}， 或者简单的实现{@link WebSocketHandler}接口
 */
public class WebSocketHander extends TextWebSocketHandler {


	    @Override
	    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
	        WebSocketUtil.addUser(session);
	    }
	    
	    
	    /**
	     * 处理客户端发送过来的消息(当客户端发送字符串的时候,我们处理的都时发送的字符串,所以其他的处理方法没写)
	     */
	    @Override
		protected void handleTextMessage(WebSocketSession session,TextMessage message) throws Exception {
	    	try {
	    		WebSocketUtil.sendMessageToConnectionUser(session, message);
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	
		}
	    

	    @Override
	    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
	        if(session.isOpen()){
	        	session.close();
	        }
	        PrintUtil.print("websocket链接出错，关闭链接......");
	        WebSocketUtil.removeUser(session);
	    }
	    

		//onClose
	    @Override
	    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
	    	System.out.println("websocket链接关闭...sessionId===>"+session.getId());
	        WebSocketUtil.removeUser(session);
	    }

	    /**
		 * 是否分段发送消息
		 */
	    @Override
	    public boolean supportsPartialMessages() {
	        return false;
	    }
	    

}
